package com.lesent.grpc.server;

import com.lesent.grpc.demo.GreeterGrpc;
import com.lesent.grpc.demo.HelloReply;
import com.lesent.grpc.demo.HelloRequest;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import io.grpc.stub.StreamObserver;

import java.io.IOException;

/**
 * @author shengtao
 * @Description:
 * @date 2018/08/14 12:03
 */
public class HelloWorldServer {

    private int port = 50051;

    private Server server;

    /**
     * 开启服务
     * @throws IOException
     */
    public void start() throws IOException {
        server = ServerBuilder.forPort(port)
                .addService(new GreeterImpl())
                .build()
                .start();

        System.out.println("service start...");
        Runtime.getRuntime().addShutdownHook(new Thread(new Runnable() {
            @Override
            public void run() {
                System.err.println("*** shutting down gRPC server since JVM is shutting down");
                HelloWorldServer.this.stop();
                System.err.println("*** server shut down");
            }
        }));
    }

    /**
     * 停止服务
     */
    private void stop() {
        if (server != null) {
            server.shutdown();
        }
    }

    // block 一直到退出程序
    private void blockUntilShutdown() throws InterruptedException {
        if (server != null) {
            server.awaitTermination();
        }
    }

    /**
     * 构建内部接口实现类
     */
    private class GreeterImpl extends GreeterGrpc.GreeterImplBase{
        @Override
        public void sayHello(HelloRequest request, StreamObserver<HelloReply> responseObserver) {
            System.out.println("service:"+request.getName());
            HelloReply reply = HelloReply.newBuilder().setMessage("相应回复，我认识").build();
            responseObserver.onNext(reply);
            responseObserver.onCompleted();
        }
    }


    public static void mian(String args[]){

        final HelloWorldServer server = new HelloWorldServer();
        server.stop();
        try {
            Thread.sleep(Integer.MAX_VALUE);
            server.blockUntilShutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
            System.out.println("safd");
    }

}
